<template>
  <div>
    <c-table-box
      ref="cTableBox"
      hide-func
      checkbox
      :no-request="noRequest"
      :other-filters="otherFilters"
      :table-config="tableConfig"
      @selection-change="selectionChange"
    >
      <template #btn>
        <c-permission v-if="type==='all'" code="all">
          <c-button opt-code="add" type="primary" @click="handleAdd">新增</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
        <c-permission v-if="type==='openup'" code="openup">
          <c-button opt-code="apply" type="primary" @click="handleApply">开业申请</c-button>
          <c-button opt-code="termination" type="primary" @click="handleTeminal">终止任务</c-button>
        </c-permission>
        <c-permission v-if="type==='execute'" code="execute">
          <c-button opt-code="execute" type="primary" @click="handleOpenExe">开业执行</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
        <c-permission v-if="type==='audit'" code="audit">
          <c-button opt-code="audit" type="primary" @click="handleResultAudit">开业结果审核</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
      </template>

    </c-table-box>
    <export-files v-if="exportVisible" title="导出" :config="exportAllConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    <!-- <apply v-if="showApply" :id="activeRowData.id" :page-show.sync="showApply" @success="refreshTable" /> -->
    <!-- <detail-page v-if="showDetail" :id="activeRowData.id" :page-show.sync="showDetail" /> -->
    <!-- <add v-if="showAdd" :page-show.sync="showAdd" @success="refreshTable" /> -->
    <open-exe v-if="showOpenExe" ref="refExeDlg" :detail-data="activeRowData" :visible.sync="showOpenExe" @success="refreshTable" />
    <result-audit v-if="showResultAudit" ref="refAuditDlg" :detail-data="activeRowData" :visible.sync="showResultAudit" @success="refreshTable" />
  </div>
</template>
<script>
import { getDictByPatchType } from '@/api/dataDict'
import { terminalTask } from '@/api/shopOpenManage'
// import apply from './apply.vue'
// import detailPage from './detail.vue'
// import add from './add.vue'
import openExe from './openExeDlg.vue'
import resultAudit from './resultAuditDlg.vue'
import { otherFiltersItem } from '@/utils'

export default {
  name: 'List',
  components: { openExe, resultAudit },

  props: {
    type: {
      type: String,
      default: ''
    },
    activeType: {
      type: String,
      default: ''
    },
    noRequest: {
      type: Boolean,
      default: false
    },
    serachFilters: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      exportVisible: false,
      typeFilters: [],
      id: '',
      delayLoading: false,
      stopLoading: false,
      doorHeadOptions: [],
      constTypeOptions: [],
      decorationFormOptions: [],
      applyBizTypeOptions: [],
      applySpecialZoneOptions: [],
      activeDataId: '',
      centerDialogVisible: false,
      loading: false,
      confirmVisible: false,
      showAdd: false,
      // showInformation: false,
      activeTabIndex: 0,
      activeName: 'all',
      activeRowData: {},
      showOpenExe: false, // 打开开业执行弹窗
      showResultAudit: false, // 打开开业结果审核弹窗
      handlefilters: [],
      showApply: false,
      showDetail: false,
      decorationRangeOptions: [], // 门店装修范围
      tableSelected: [], // 当前所选中表格行数据
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopOpening/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        sort: 'createTime',
        // 表格字段动态配置
        setting: [
          {
            prop: 'openingCode',
            label: '开业记录号',
            minWidth: '110',
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },
          {
            prop: 'constCode',
            label: '门店建设项目号',
            minWidth: '110'
          },
          {
            prop: 'schedule',
            label: '门店开业进度',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'OPEN_SCHEDULE'
            }

          },
          {
            prop: 'constSchedule',
            label: '门店建设整体进度',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BEFORE_CONST_SCHEDULE'
            }
          },
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: '110'
          },
          {
            prop: 'clientName',
            label: '客户',
            minWidth: '110'
          },
          {
            prop: 'shopName',
            label: '门店',
            minWidth: '110'
          },
          {
            prop: 'marketType',
            label: '报图类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'MARKET_TYPE'
            },
            minWidth: '110'
          },
          {
            prop: 'constType',
            label: '门店建设类型',
            render: (creat, row) => {
              if (!row.constType) {
                return
              }
              let list = []
              if (typeof (row.constType) === 'string') {
                list = row.constType.split(',')
              } else {
                list = row.constType
              }
              const arr = []
              this.constTypeOptions.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            },
            minWidth: '110'
          },
          {
            prop: 'bizmanType',
            label: '商家类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BIZMAN_TYPE'
            },
            minWidth: '110'
          },
          {
            prop: 'decorationRange',
            label: '装修范围',
            render: (creat, row) => {
              if (!row.decorationRange) {
                return
              }
              let list = []
              if (typeof (row.decorationRange) === 'string') {
                list = row.decorationRange.split(',')
              } else {
                list = row.decorationRange
              }
              const arr = []
              this.decorationRangeOptions.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            },
            minWidth: '110'
          },
          {
            prop: 'isHandover',
            label: '是否交接市场',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: '110'
          },
          {
            prop: 'expectOpenTime',
            label: '预计开业时间',
            type: 'date',
            minWidth: '130'
          },
          {
            prop: 'isDelay',
            label: '开业是否延期',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: '100'
          },
          {
            prop: 'actualActivityStartTime',
            label: '实际开业开始时间',
            type: 'date',
            minWidth: '130'
          },
          {
            prop: 'actualActivityEndTime',
            label: '实际开业结束时间',
            type: 'date',
            minWidth: '130'
          }
        ]
      }
    }
  },
  computed: {
    otherFilters() {
      return [...this.serachFilters, ...this.typeFilters]
    },
    selectedIds() {
      return this.tableSelected.map(row => {
        return row.id
      })
    },
    exportAllConfig() {
      return [{
        code: 'export',
        name: '门店开业管理',
        dataApi: '/slm-admin/api/v1/shopOpening/export?type=0',
        selectedRows: this.tableSelected,
        paramsRaw: {},
        headers: { 'Permission-perCode': 'openmanage' },
        filtersRaw: this.otherFilters,
        queryField: 'id'
      }]
    }
  },
  watch: {
    type: {
      handler(v) {
        this.setOtherFilters(v)
      },
      immediate: true
    },
    serachFilters: {
      handler(v) {
        if (this.activeType !== this.type) return
        this.refreshTable('')
      }
    }
  },
  activated() {
    if (this.ready && this.refreshTable) {
      this.refreshTable()
    }
  },
  deactivated() {
    this.ready = true
  },
  created() {
    this.getDictByPatchTypeAll()
  },
  methods: {
    async getDictByPatchTypeAll() {
      const { CONST_TYPE, DECORATION_RANGE } =
       await getDictByPatchType(['CONST_TYPE', 'DECORATION_RANGE'])
      this.constTypeOptions = CONST_TYPE // 门店建设
      this.decorationRangeOptions = DECORATION_RANGE// 门店装修范围
    },

    selectionChange(v) {
      this.tableSelected = v
    },

    // 导出
    handleExport() {
      this.exportVisible = true
    },
    handleDetail(val) {
      this.$router.push({ name: 'OpenDetail', query: { id: val.id }})
    },

    // 设置过滤条件
    setOtherFilters(v) {
      switch (v) {
        case 'all':
          this.typeFilters = []
          break
        case 'openup':
          this.typeFilters = [
            otherFiltersItem('constSchedule', 'P', '<>'),
            otherFiltersItem('isEnd', '1', '<>'),
            otherFiltersItem('schedule', 'A', '=')
          ]
          break
        case 'execute':
          this.typeFilters = [
            otherFiltersItem('constSchedule', 'P', '<>'),
            otherFiltersItem('isEnd', '1', '<>'),
            otherFiltersItem('schedule', 'C', '=')]
          break
        case 'audit':
          this.typeFilters = [
            otherFiltersItem('constSchedule', 'p', '<>'),
            otherFiltersItem('isEnd', '1', '<>'),
            otherFiltersItem('schedule', 'D', '=')]
          break
      }
    },
    // 开业执行
    handleOpenExe() {
      if (!this.singleJudge(this.tableSelected, '开业执行', true)) {
        return
      }
      this.showOpenExe = true
      this.activeRowData = this.tableSelected[0]
    },
    // 开业结果审核
    handleResultAudit(data) {
      if (!this.singleJudge(this.tableSelected, '审核', true)) {
        return
      }
      this.showResultAudit = true
      this.activeRowData = this.tableSelected[0]
    },
    // 开业申请
    handleApply() {
      if (!this.singleJudge(this.tableSelected, '开业申请', true)) {
        return
      }
      this.$router.push({ name: 'OpenApply', query: { id: this.tableSelected[0].id }})
      // this.activeRowData = this.tableSelected[0]
      // this.showApply = true
    },
    handleAdd() {
      this.$router.push({ name: 'OpeningAdd' })
    },
    // 终止
    handleTeminal() {
      if (!this.singleJudge(this.tableSelected, '终止', true)) {
        return
      }
      this.$prompt('终止原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        terminalTask({
          id: this.tableSelected[0].id,
          endReason: value,
          schedule: this.tableSelected[0].schedule,
          constCode: this.tableSelected[0].constCode
        }).then(res => {
          if (res.success === 1) {
            this.$message({
              type: 'success',
              message: '已终止'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    // 刷新表格
    refreshTable(v = 'onPage') {
      this.$nextTick(() => {
        this.$refs.cTableBox.initTableData(v)
      })
    },

    // 导出成功
    handleExportSuccess() {
      this.$message.success('导出成功！')
    },
    // 导入成功
    handleImportSuccess() {
      this.$message.success('导入成功！')
    }
  }
}
</script>
